define(["backbone", "_template", "jquery", "_queryConditions", "_cartData", "_base", "_global", "layer_m", "qrcode", "_netPointDialog"],
    function (Backbone, template, $, _qc, _CD, _base, _gl, layer, QRCode, _netPointDialog) {
        return Backbone.View.extend({
            el: '#pageSwitch',
            eventType: "click",
            events: {
                "change #sureAddressInfo": "sureAddressInfo",
                "click #sureAddress": "sureAddress",
                "click #getValidateCode": "getValidateCode",
                "click #sureHelpBuy": "surePay",
                "click #openNetPointDialog": "openNetPointDialog"
            },
            initialize: function (opts) {

            },
            render: function (opts) {
                var scope = this;
                scope.clearTimer();
                var goodsAllBuy = _CD.getAllBuy();
                var totalPrice = 0;
                for (var i = 0, len = goodsAllBuy.length; i < len; i++) {
                    totalPrice = _base.accAdd(totalPrice, _base.accMul(parseFloat(goodsAllBuy[i].numb), parseFloat(goodsAllBuy[i].price)));
                }
                scope.totalPrice = totalPrice;
                $(scope.el).html(template("templatePay", {
                    totalPrice: totalPrice,
                    phoneLabel: "代购员帐号",
                    isShowOrderWay: false,
                    isShowOrderNote: true,
                    surePayId: "sureHelpBuy"
                }));
                scope.loadAddress();
                _gl.backTop();
            },
            surePay: function () {
                var scope = this;
                var salesmanAccount = $("#salesmanAccount").val();
                var validateCode = $("#validateCode").val();
                var orderInfo = $("#orderInfo").val();
                if (salesmanAccount.length < 1) {
                    _gl.tips({ content: '代购员帐号不能为空！', id: '#salesmanAccount' });
                    return;
                }
                if (validateCode.length < 1) {
                    _gl.tips({ content: '验证码不能为空！', id: '#validateCode' });
                    return;
                }
                if (!salesmanAccount.match(/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/)) {
                    _gl.tips({ content: '您输入的代购员帐号有误！', id: '#salesmanAccount' });
                    return;
                }
                var url = '/Api/OrderCreate';
                var post = $.post(url, { mobile: salesmanAccount, pointid: _qc.getNetPoint().id, vcode: validateCode, goods: JSON.stringify(_CD.getAllBuy()), remark: orderInfo, payway: 0 }, function (data) {
                    if (data.success) {
                        var msg = data.message;
                        $("#wizard-3").addClass("active");
                        _CD.delBuy();
                        scope.paySuccess({ info: '您的订单创建成功' });
                    }
                    else {
                        _gl.tips({ content: data.message, id: '#validateCode' });
                    }
                });
                post.error(function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("OrderCreate error：" + "status=" + XMLHttpRequest.status + " && text=" + textStatus);
                });
            },
            // 点击关闭按钮，关闭弹窗
            closeDialog: function () {
                var scope = this;
                $(".dialog-closeBtn").off(scope.eventType).on(scope.eventType, function () {
                    scope.closeDialogConfirm();
                });
                $(".laymshade").off(scope.eventType).on(scope.eventType, function () {
                    scope.closeDialogConfirm();
                });
            },
            // 点击layer蒙版，关闭
            closeDialogConfirm: function () {
                var scope = this;
                var layerIndex = _gl.confirm({
                    title: '温馨提示',
                    content: '确定放弃本次付款吗？',
                    btnName: ['确定', '取消'],
                    yes: function () {
                        _gl.close(layerIndex);

                    },
                    no: function () {
                        scope.clearTimer();
                        _gl.closeAll();
                        return false;
                    }
                });

            },
            sureAddressInfo: function () {
                var $sureAddressInfo = $("#sureAddressInfo");
                if ($sureAddressInfo.is(":checked")) {
                    $("#dialog-step-1").hide();
                    $sureAddressInfo.hide();
                    $("#dislog-step-2").show();
                    $("#wizard-2").addClass("active");
                }
            },
            // 加载地址
            loadAddress: function () {
                var $payAddress = $('#payAddress');
                $payAddress.text('玩命加载中...');
                //获取网点地址
                var url = _gl.getAjaxUrl().netPointInfo;
                var post = $.post(url, { pointid: _qc.getNetPoint().id }, function (data) {
                    if (data.success) {
                        $payAddress.text(data.result.Address);
                    }
                    else {
                        alert("GetNetPointInfo warning：" + data.message);
                    }
                });
                post.error(function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("GetNetPointInfo error：" + "status=" + XMLHttpRequest.status + " && text=" + textStatus);
                });
            },
            // 确认地址
            sureAddress: function () {
                var $sureAddressInfo = $("#sureAddressInfo");
                if (!$sureAddressInfo.is(":checked")) {
                    _gl.tips({ content: "请确认地址及信息!", id: "#sureAddressInfo" });
                }
            },
            getValidateCode: function (e) {
                var $this = $(e.target);
                var $salesmanAccount = $("#salesmanAccount");
                var phone = $salesmanAccount.val();
                var mobile = $("#salesmanAccount").val();
                var url = _gl.getAjaxUrl().sendVerifCode;
                if (phone.length < 1) {
                    _gl.tips({ content: "请输入您的代购员帐号", id: "#salesmanAccount" });
                    return false;
                }
                else if (!phone.match(/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/)) {
                    _gl.tips({ content: "您输入的代购员帐号非法", id: "#salesmanAccount" });
                    return false;
                }
                var MAXTIME = 60;
                var maxTime = MAXTIME;
                var tHtml = $this.html();
                window.getValidateCodeTimer = setInterval(function () {
                    if (maxTime <= 0) {
                        clearInterval(window.getValidateCodeTimer);
                        maxTime = MAXTIME
                        $this.html(tHtml);
                        $this.prop("disabled", false);
                    } else {
                        maxTime--;
                        $this.html(maxTime + "秒后再发送");
                        $this.prop("disabled", true);
                    }
                }, 1000);
                var post = $.post(url, { mobile: mobile, opt: 1 }, function (data) {
                    if (data.success) {
                        var msg = data.message;
                    }
                    else {
                        _gl.tips({ content: data.message, id: "#salesmanAccount" });
                        clearInterval(window.getValidateCodeTimer);
                        maxTime = MAXTIME;
                    }
                });
                post.error(function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("SendVerifCode error：" + "status=" + XMLHttpRequest.status + " && text=" + textStatus);
                });
            },
            // 付款成功
            paySuccess: function (d) {
                this.clearTimer();
                _gl.closeAll();
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: false,
                    shadeClose: false,
                    area: ['550px', '250px'],
                    content: '<div style="padding:30px 30px;text-align:center;">' +
                        '<p style="font-size:18px;padding:30px 0;">' + d.info + '，<span style="margin:0 5px;" id="gotoHomeTime">10</span>秒后返回首页。</p>' +
                        '<p><a href="javascript:void(0)" id="goonShoppingBtn"  class="btn btn-danger" style="margin-right:5px;">继续购物</a>' +
                        '<a href="javascript:void(0)" id="stopShoppingBtn"  class="btn btn-danger" style="margin-left:5px;">结束购物</a></p>' +
                        '</div>'
                });
                var maxtimer = 10;
                var $gotoHomeTime = $("#gotoHomeTime");

                var refresh = function () {
                    window.location.href = window.location.href.indexOf("#") > 0 ? window.location.href.split("#")[0] : window.location.href;
                };
                window.gotoHomeTimer = setInterval(function () {
                    if (maxtimer <= 0) {
                        maxtimer = 10;
                        _qc.removeNetPoint();
                        _CD.clear();
                        clearInterval(window.gotoHomeTimer);
                        refresh();
                        return;
                    }
                    maxtimer--;
                    $gotoHomeTime.html(maxtimer);
                }, 1000);
                $("#goonShoppingBtn").off("click").on("click", function () {
                    clearInterval(window.gotoHomeTimer);
                    refresh();
                });
                $("#stopShoppingBtn").off("click").on("click", function () {
                    _qc.removeNetPoint();
                    _CD.clear();
                    clearInterval(window.gotoHomeTimer);
                    refresh();
                });
            },
            clearTimer: function () {
                if (!!window.scanCountdownTimer) {
                    clearInterval(scanCountdownTimer);
                }
                if (!!window.getValidateCodeTimer) {
                    clearInterval(getValidateCodeTimer);
                }
                if (!!window.payCountdownTimer) {
                    clearInterval(window.payCountdownTimer);
                }
                if (!!window.gotoHomeTimer) {
                    clearInterval(window.gotoHomeTimer);
                }
            },
            openNetPointDialog: function () {
                _netPointDialog.init();
            }
        });
    });